package com.zretc.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.zretc.entity.Admin;
import com.zretc.entity.User;
import com.zretc.service.AdminService;
import com.zretc.service.UserService;
import com.zretc.service.impl.AdminServiceImpl;
import com.zretc.service.impl.UserServiceImpl;

/**
 * Servlet implementation class AdminServlet
 */
@WebServlet("/back/AdminUserManagementServlet")
@MultipartConfig
public class AdminUserManagementServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserService userService = new UserServiceImpl();
	private AdminService adminService = new AdminServiceImpl();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AdminUserManagementServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		   // 设置请求参数的编码格式
		request.setCharacterEncoding("UTF-8");
		// 接收请求中的参数op,请求操作标识
		String op = request.getParameter("op");
		    
		if (op == "" || "find".equals(op)) {
			//查询买家信息
			find(request,response);
		}else if ("doLogin".equals(op)) {
			//管理员登录
			doLogin(request,response);
		}else if ("doLogout".equals(op)) {
			//管理员登出
			doLogout(request,response);
		}else if ("deleteByUserId".equals(op)) {
			//删除买家信息
			doDeleteByUserId(request,response);
		}else if ("updateByUserId".equals(op)) {
			//修改买家信息
			doUpdateByUserId(request,response);
		}
	}
	
	
	private void doLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession();
		session.removeAttribute("admin");
		response.sendRedirect("adminSignIn.jsp");
		
	}

	private void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 调度器
				// 1.调用业务层逻辑
				String adminAccount = request.getParameter("adminAccount");
				String adminPassword = request.getParameter("adminPassword");
				Admin admin = adminService.adminLogin(adminAccount, adminPassword);
				if (admin != null) {
					// 登录成功
					// 用户信息存储在session会话作用域中
					HttpSession session = request.getSession();
					session.setAttribute("admin", admin);

					// 获取复选框的值
					String rememberPassword = request.getParameter("rememberPassword");

					// 用户选择记住密码
					if (rememberPassword != null) {
						// 通过Servlet像cookie添加用户信息并发送给HTTP
						Cookie cookie = new Cookie(adminAccount, adminPassword);
						// 设置cookie有效时间
						cookie.setMaxAge(60 * 5);
						// 将cookie发送给HTTP
						response.addCookie(cookie);
					} else {
						// 用户选择不记住密码，通过Servlet删除Cookie（setMaxAge(0)），读取并存储新Cookie并发送给HTTP
						Cookie[] cookies = request.getCookies();
						Cookie cookie = null;
						for (int i = 0; i < cookies.length; i++) {
							cookie = cookies[i];
							if (cookie.getName().equals(adminAccount)) {
								cookie.setMaxAge(0);
								response.addCookie(cookie);
							}
							if (cookie.getValue().equals(adminPassword)) {
								cookie.setMaxAge(0);
								response.addCookie(cookie);
							}
						}
					}
					// 重定向到首页
					response.sendRedirect("adminUserManagement.jsp");
				} else {
					// 登录失败
					// 重定向到登录页面
					response.sendRedirect("adminSignIn.jsp?loginErrorMessage=error");
				}
		
	}

	/**
	 * 查询买家信息
	 * @throws IOException 
	 */

	private void find(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		String nameKey = request.getParameter("nameKey");
		Map<String, String> params = new HashMap<String,String>();
		params.put("nameKey", nameKey);
		List<User> user = userService.findByUserCondition(params);
		
		Gson gson = new Gson();
		String jsonObject = gson.toJson(user);

		response.setContentType("appliction/json");
		response.getWriter().write(jsonObject);
	
		
	}
	
	/**
	 * 查询修改买家信息
	 * @throws IOException 
	 */

	private void doUpdateByUserId(HttpServletRequest request, HttpServletResponse response) throws IOException {

		//解析json字符串
		String jsonString = request.getParameter("updateUser");
		Gson gson = new Gson();
		User user = gson.fromJson(jsonString, User.class);
		userService.updateUserByUserId(user);
		find(request, response);
	}
	
	/**
	 * 删除买家信息
	 * @throws IOException 
	 */

	private void doDeleteByUserId(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		Integer userId = Integer.valueOf(request.getParameter("userId"));
		userService.deleteByUserId(userId);
		find(request, response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
